<script setup>
import { ref } from 'vue'
import { addBookService, editBookService } from '@/api/book.js'
import { addAvatarService, imageUrlToFileObject } from '@/api/avatar.js'
let isEdit = undefined
const dialogVisible = ref(false)
const formRef = ref()
const uploadRef = ref()
const imageUrl = ref('')
const formModel = ref({
  bookName: '',
  author: '',
  deposit: '',
  position: '',
  num: '',
  imgUrl: '',
  file: ''
})
const rules = {
  bookName: [{ required: true, message: '请输入书籍名称', trigger: 'change' }],
  author: [{ required: true, message: '请输入作者', trigger: 'change' }],
  deposit: [
    { required: true, message: '请输入押金', trigger: 'change' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '押金必须是两位小数以内的非负浮点数',
      trigger: 'change'
    }
  ],
  position: [
    { required: true, message: '请输入书架的具体位置', trigger: 'change' }
  ],
  num: [
    { required: true, message: '请输入数量', trigger: 'change' },
    {
      pattern: /^[1-9]\d*|0$/,
      message: '数量必须是非负整数',
      trigger: 'change'
    }
  ]
}

const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()
  console.log(formModel.value.file)
  if (imageUrl.value !== '' && formModel.value.file !== undefined) {
    const res = await addAvatarService(formModel.value.file)
    formModel.value.imgUrl = res.data.data
  }
  if (isEdit) {
    await editBookService(formModel.value)
    ElMessage.success('编辑成功')
  } else {
    await addBookService(formModel.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  emit('success')
}

const onSelectFile = (uploadFile) => {
  // 基于 FileReader 读取图片做预览
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.file = uploadFile.raw
}

// 组件对外暴露一个方法 open，基于open传来的参数，区分添加还是编辑
// open({})  => 表单无需渲染，说明是添加
// open({ id, cate_name, ... })  => 表单需要渲染，说明是编辑
// open调用后，可以打开弹窗
const open = (row) => {
  dialogVisible.value = true
  formModel.value = { ...row } // 添加 → 重置了表单内容，编辑 → 存储了需要回显的数据
  imageUrl.value = ''
  isEdit = formModel.value.id
  if (isEdit) {
    imageUrlToFileObject(formModel.value.imgUrl)
      .then((blobURL) => {
        imageUrl.value = blobURL
      })
      .catch((error) => {
        console.error('Error occurred:', error)
      })
  }
}

// 将网络图片地址转换为 File 对象的函数

// 向外暴露方法
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑书籍' : '添加书籍'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="书籍名称" prop="bookName">
        <el-input
          v-model="formModel.bookName"
          placeholder="请输入书籍名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="formModel.author"
          placeholder="请输入作者"
        ></el-input>
      </el-form-item>
      <el-form-item label="押金" prop="deposit">
        <el-input
          v-model="formModel.deposit"
          placeholder="请输入押金"
        ></el-input>
      </el-form-item>
      <el-form-item label="位置" prop="position">
        <el-input
          v-model="formModel.position"
          placeholder="请输入书籍所在书架具体位置"
        ></el-input>
        <el-text>如A1书架第一层简称为A1-1</el-text>
      </el-form-item>
      <el-form-item label="数量" prop="num">
        <el-input
          v-model="formModel.num"
          placeholder="请输入书籍现存数量"
        ></el-input>
      </el-form-item>
      <el-form-item label="书籍图片" prop="file">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="onSelectFile"
          multiple
        >
          <img v-if="imageUrl[0] === 'b'" :src="imageUrl" class="book-pic" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <br />

      <el-button
        @click="uploadRef.$el.querySelector('input').click()"
        type="primary"
        :icon="Plus"
        size="large"
        >选择书籍图片</el-button
      >
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .book-pic {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
